﻿using CCWin.SkinClass;
using Google.Protobuf.WellKnownTypes;
using HirelSeriesH.Entity;
using HirelSeriesH.Tools;
using MySql.Data.MySqlClient;
using Org.BouncyCastle.Crypto;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HirelSeriesH
{
    public partial class ConfigurationForm : UIForm
    {
        private bool isWorker;
        private string person;
        private string IDs;
        private DataTable dataTable;

        public delegate void RefreshDelegate(); // 子窗口声明定义委托 refresh() 
        public event RefreshDelegate refresh;

        public ConfigurationForm(bool isWorker, string person, string ids)
        {
            InitializeComponent();
            this.cfgGrid.AutoGenerateColumns = false;
            this.IDs = ids;
            this.person = person;
            this.isWorker = isWorker;
            if (isWorker)
            {
                this.panelEngineer.Visible = false;
                this.panelWorker.Visible = true;
            }
            else
            {
                this.panelEngineer.Visible = true;
                this.panelWorker.Visible = false;
                this.panelWorker.Width = 0;
                this.panelEngineer.Location = new Point(this.panelWorker.Location.X - 1, this.panelWorker.Location.Y);
            }
            ConfigDetailForm.refreshData += refreshData;
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            ConfigDetailForm configDetail = new ConfigDetailForm(this.person, "create", null);
            configDetail.Show(this);
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            if (this.cfgGrid.CurrentRow == null)
            {
                UIMessageDialog.ShowMessageDialog(this, "请先选择要修改的测试参数方案记录", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }
            int index = cfgGrid.CurrentRow.Index;
            ConfigDetailForm configDetail = new ConfigDetailForm(this.person, "modify", this.dataTable.Rows[index]);
            configDetail.Show(this);
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            if (this.cfgGrid.CurrentRow == null)
            {
                UIMessageDialog.ShowMessageDialog(this, "请先选择要查看的测试参数方案记录", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }
            int index = cfgGrid.CurrentRow.Index;
            ConfigDetailForm configDetail = new ConfigDetailForm(this.person, "read", this.dataTable.Rows[index]);
            configDetail.Show(this);
        }

        private void ConfigurationForm_Load(object sender, EventArgs e)
        {
            DataSet dataSet = DBHelper.GetDataSet(DBSql.SELECT_HTRB_TEST_PARAMETERR, 1);
            this.dataTable = dataSet.Tables[0];
            this.cfgGrid.DataSource = this.dataTable;
        }
        private void refreshData()
        {
            DataSet dataSet = DBHelper.GetDataSet(DBSql.SELECT_HTRB_TEST_PARAMETERR, 1);
            this.dataTable = dataSet.Tables[0];
            this.cfgGrid.DataSource = this.dataTable;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!UIMessageDialog.ShowMessageDialog(this, "是否确定删除当前所选则的测试参数方案？", UILocalize.AskTitle, true, UIStyle.Colorful))
            {
                return;
            }
            else
            {
                if (this.cfgGrid.CurrentRow == null)
                {
                    UIMessageDialog.ShowMessageDialog(this, "请先选择要删除的测试参数方案记录", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                    return;
                }
                int index = cfgGrid.CurrentRow.Index;
                MySqlParameter[] paras = new MySqlParameter[] { new MySqlParameter("@ID", this.dataTable.Rows[index]["ID"].ToString()) };
                //删除测试参数方案
                DBHelper.ExecuteNonQuery(DBSql.DELE_HTRB_TEST_PARAMETERR, 1, paras);
                UIMessageDialog.ShowMessageDialog(this, "删除测试参数方案成功", UILocalize.InfoTitle, false, UIStyle.Colorful);
                this.ConfigurationForm_Load(sender, e);

            }
        }

        private void BtnSelect_Click(object sender, EventArgs e)
        {
            string criteria = this.TextBoxCriteria.Text.Trim();
            DataSet dataSet;
            if (criteria == null || criteria.Length == 0)
            {
                dataSet = DBHelper.GetDataSet(DBSql.SELECT_HTRB_TEST_PARAMETERR, 1);
            }
            else
            {
                MySqlParameter[] paras = new MySqlParameter[] { new MySqlParameter("@ParaName", "%" + criteria + "%") };
                dataSet = DBHelper.GetDataSet(DBSql.SELECT_HTRB_TEST_PARAMETERR_CRITERIA, 1, paras);
            }
            this.dataTable = dataSet.Tables[0];
            this.cfgGrid.DataSource = this.dataTable;
        }

        private void TextBoxCriteria_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.BtnSelect_Click(sender, e);
            }
        }

        private void btnPick_Click(object sender, EventArgs e)
        {
            if (this.cfgGrid.CurrentRow == null)
            {
                UIMessageDialog.ShowMessageDialog(this, "请先选择一条测试参数方案记录", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }
            int index = cfgGrid.CurrentRow.Index;
            TestParameter testParameter = new TestParameter();
            testParameter.ID = this.dataTable.Rows[index]["ID"].ToString();
            testParameter.ParaName = this.dataTable.Rows[index]["ParaName"].ToString();
            testParameter.Remarks = this.dataTable.Rows[index]["Remarks"].ToString();
            testParameter.ProductModel = this.dataTable.Rows[index]["ProductModel"].ToString();
            testParameter.BatchNumber = this.dataTable.Rows[index]["BatchNumber"].ToString();
            testParameter.CheckInterval = decimal.Parse(this.dataTable.Rows[index]["CheckInterval"].ToString());
            testParameter.PowerStepConfig = this.dataTable.Rows[index]["PowerStepConfig"].ToString();

            testParameter.HighTemp = decimal.Parse(this.dataTable.Rows[index]["HighTemp"].ToString());
            testParameter.LowTemp = decimal.Parse(this.dataTable.Rows[index]["LowTemp"].ToString());
            testParameter.HighTime = decimal.Parse(this.dataTable.Rows[index]["HighTime"].ToString());
            testParameter.LowTime = decimal.Parse(this.dataTable.Rows[index]["LowTime"].ToString());
            testParameter.XieLv = decimal.Parse(this.dataTable.Rows[index]["XieLv"].ToString());
            testParameter.TestCycs = decimal.Parse(this.dataTable.Rows[index]["TestCycs"].ToString());
            testParameter.BeforTemp = decimal.Parse(this.dataTable.Rows[index]["BeforTemp"].ToString());
            testParameter.BeforTime = decimal.Parse(this.dataTable.Rows[index]["BeforTime"].ToString());
            testParameter.AfterTemp = decimal.Parse(this.dataTable.Rows[index]["AfterTemp"].ToString());
            testParameter.AfterTime = decimal.Parse(this.dataTable.Rows[index]["AfterTime"].ToString());
            testParameter.IsLineContrl = this.dataTable.Rows[index]["IsLineContrl"].ToString();
            testParameter.StratPos = this.dataTable.Rows[index]["StratPos"].ToString();
            testParameter.TempContrl = this.dataTable.Rows[index]["TempContrl"].ToString();
            testParameter.Ysfz = this.dataTable.Rows[index]["Ysfz"].ToString();


            bool isStatic;
            bool.TryParse(this.dataTable.Rows[index]["isStatic"].ToString(), out isStatic);
            testParameter.isStatic = isStatic;

            string[] ids = IDs.Split(',');
            Global.Global.ChannelListTemp.Clear();

            List<Channel> channelList = Global.Global.ChannelList;
            foreach (Channel channel in channelList)
            {
                for (int i = 0; i < ids.Length; i++)
                {
                    if ((ids[i] != null) && (ids[i] != "") && (ids[i].Length > 0))
                    {
                        if (ids[i] == channel.ID)
                        {
                            Global.Global.ChannelListTemp.Add(channel);
                        }
                    }
                }
            }

            for (int i = 0; i < Global.Global.ChannelListTemp.Count; i++)
            {
                if (Global.Global.ChannelListTemp[i].State != "stop")
                {
                    UIMessageDialog.ShowMessageDialog(this, Global.Global.ChannelListTemp[i].ChannelName + "处于非空闲状态，不能中途改变测试参数。", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                    return;
                }
                /*if (Global.Global.ChannelListTemp[i].Power != null && (Global.Global.ChannelListTemp[i].Power.IsOpen || Global.Global.ChannelListTemp[i].Power.IsUpDown))
                {
                    UIMessageDialog.ShowMessageDialog(this, Global.Global.ChannelListTemp[i].ChannelName + "电源处于开启状态，请先关闭电源。", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                    return;
                }*/
            }

            //温箱参数
            if (Global.Global.PtcBox.IsOpen)
            {
                testParameter.HighTemp = Global.Global.PtcBox.HighTemp;
                testParameter.LowTemp = Global.Global.PtcBox.LowTemp;
                testParameter.HighTime = Global.Global.PtcBox.HighTime;
                testParameter.LowTime = Global.Global.PtcBox.LowTime;
                testParameter.XieLv = Global.Global.PtcBox.XieLv;
                testParameter.TestCycs = Global.Global.PtcBox.TestCycs;
                testParameter.BeforTemp = Global.Global.PtcBox.BeforTemp;
                testParameter.BeforTime = Global.Global.PtcBox.BeforTime;
                testParameter.AfterTemp = Global.Global.PtcBox.AfterTemp;
                testParameter.AfterTime = Global.Global.PtcBox.AfterTime;
                testParameter.IsLineContrl = Global.Global.PtcBox.IsLineContrl;
                testParameter.StratPos = Global.Global.PtcBox.StratPos;
                testParameter.TempContrl = Global.Global.PtcBox.TempContrl;
                testParameter.Ysfz = Global.Global.PtcBox.Ysfz;
            }
            else
            {
                Global.Global.PtcBox.HighTemp = testParameter.HighTemp;
                Global.Global.PtcBox.LowTemp = testParameter.LowTemp;
                Global.Global.PtcBox.HighTime = testParameter.HighTime;
                Global.Global.PtcBox.LowTime = testParameter.LowTime;
                Global.Global.PtcBox.XieLv = testParameter.XieLv;
                Global.Global.PtcBox.TestCycs = testParameter.TestCycs;
                Global.Global.PtcBox.BeforTemp = testParameter.BeforTemp;
                Global.Global.PtcBox.BeforTime = testParameter.BeforTime;
                Global.Global.PtcBox.AfterTemp = testParameter.AfterTemp;
                Global.Global.PtcBox.AfterTime = testParameter.AfterTime;
                Global.Global.PtcBox.IsLineContrl = testParameter.IsLineContrl;
                Global.Global.PtcBox.StratPos = testParameter.StratPos;
                Global.Global.PtcBox.TempContrl = testParameter.TempContrl;
                Global.Global.PtcBox.Ysfz = testParameter.Ysfz;

                //更新数据库状态
                MySqlParameter[] paras = new MySqlParameter[] {
                                         new MySqlParameter("@HighTemp", testParameter.HighTemp.ToString()),
                                         new MySqlParameter("@LowTemp", testParameter.LowTemp.ToString()),
                                         new MySqlParameter("@HighTime", testParameter.HighTime.ToString()),
                                         new MySqlParameter("@LowTime", testParameter.LowTime.ToString()),
                                         new MySqlParameter("@IsLineContrl", testParameter.IsLineContrl),
                                         new MySqlParameter("@XieLv", testParameter.XieLv.ToString()),
                                         new MySqlParameter("@TestCycs", testParameter.TestCycs.ToString()),
                                         new MySqlParameter("@StratPos", testParameter.StratPos),
                                         new MySqlParameter("@TempContrl", testParameter.TempContrl),
                                         new MySqlParameter("@BeforTemp", testParameter.BeforTemp.ToString()),
                                         new MySqlParameter("@BeforTime", testParameter.BeforTime.ToString()),
                                         new MySqlParameter("@AfterTemp", testParameter.AfterTemp.ToString()),
                                         new MySqlParameter("@AfterTime", testParameter.AfterTime.ToString()),
                                         new MySqlParameter("@Ysfz", testParameter.Ysfz),
                                         new MySqlParameter("@ID", Global.Global.PtcBox.ID) };
                DBHelper.ExecuteNonQuery(DBSql.UPDATE_PTC_BOX, 1, paras);

                foreach (var chn in Global.Global.ChannelList)
                {
                    if (chn.TestParameter == null)
                    {
                        continue;
                    }
                    chn.TestParameter.HighTemp = Global.Global.PtcBox.HighTemp;
                    chn.TestParameter.LowTemp = Global.Global.PtcBox.LowTemp;
                    chn.TestParameter.HighTime = Global.Global.PtcBox.HighTime;
                    chn.TestParameter.LowTime = Global.Global.PtcBox.LowTime;
                    chn.TestParameter.XieLv = Global.Global.PtcBox.XieLv;
                    chn.TestParameter.TestCycs = Global.Global.PtcBox.TestCycs;
                    chn.TestParameter.BeforTemp = Global.Global.PtcBox.BeforTemp;
                    chn.TestParameter.BeforTime = Global.Global.PtcBox.BeforTime;
                    chn.TestParameter.AfterTemp = Global.Global.PtcBox.AfterTemp;
                    chn.TestParameter.AfterTime = Global.Global.PtcBox.AfterTime;
                    chn.TestParameter.IsLineContrl = Global.Global.PtcBox.IsLineContrl;
                    chn.TestParameter.StratPos = Global.Global.PtcBox.StratPos;
                    chn.TestParameter.TempContrl = Global.Global.PtcBox.TempContrl;
                    chn.TestParameter.Ysfz = Global.Global.PtcBox.Ysfz;
                }
            }

            //获得步骤中使用了哪些电源，并按照从小到大排序
            List<string> powerStrList = PowerPack.getPowerStrByStep(testParameter.PowerStepConfig);
            if (powerStrList.Count <= 0) {

                UIMessageDialog.ShowMessageDialog(this, "电源步骤配置有误，请重新确认。", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }

            string powerStr = string.Join(",", powerStrList);

            if (Global.Global.powerPackList.ContainsKey(powerStr))
            {
                PowerPack usedPowerPack = Global.Global.powerPackList[powerStr];

                //判断所选通道是否与正在使用电源组的通道相同
                var isAllSame = usedPowerPack.ChannelList
                    .OrderBy(each => each.Index)
                    .Zip(Global.Global.ChannelListTemp.OrderBy(each => each.Index), (item1, item2) => new {
                        IsIndexSame = item1.Index == item2.Index
                    });

                if (usedPowerPack.PowerStepConfig.Equals(testParameter.PowerStepConfig) || (usedPowerPack.ChannelList.Count == Global.Global.ChannelListTemp.Count && isAllSame.All(each => each.IsIndexSame)))
                {
                    //完全相同 则可以使用


                    for (int i = 0; i < Global.Global.ChannelListTemp.Count; i++)
                    {
                        Channel nowChannel = Global.Global.ChannelListTemp[i];
                        nowChannel.PowerPack = usedPowerPack;

                        if (!usedPowerPack.ChannelList.Contains(nowChannel))
                        {
                            usedPowerPack.ChannelList.Add(nowChannel);
                        }


                        Global.Global.ChannelListTemp[i].State = "stop";
                        Global.Global.ChannelListTemp[i].RunningTime = new TimeSpan(0, 0, 0);

                        TestParameter tpr = new TestParameter();
                        tpr.ID = testParameter.ID;
                        tpr.ParaName = testParameter.ParaName;
                        tpr.Remarks = testParameter.Remarks;
                        tpr.ProductModel = testParameter.ProductModel;
                        tpr.BatchNumber = testParameter.BatchNumber;
                        tpr.CheckInterval = testParameter.CheckInterval;

                        tpr.PowerStepConfig = testParameter.PowerStepConfig;

                        tpr.HighTemp = testParameter.HighTemp;
                        tpr.LowTemp = testParameter.LowTemp;
                        tpr.HighTime = testParameter.HighTime;
                        tpr.LowTime = testParameter.LowTime;
                        tpr.XieLv = testParameter.XieLv;
                        tpr.TestCycs = testParameter.TestCycs;
                        tpr.BeforTemp = testParameter.BeforTemp;
                        tpr.BeforTime = testParameter.BeforTime;
                        tpr.AfterTemp = testParameter.AfterTemp;
                        tpr.AfterTime = testParameter.AfterTime;
                        tpr.IsLineContrl = testParameter.IsLineContrl;
                        tpr.StratPos = testParameter.StratPos;
                        tpr.TempContrl = testParameter.TempContrl;
                        tpr.Ysfz = testParameter.Ysfz;

                        tpr.isStatic = testParameter.isStatic;


                        if (!Global.Global.ChannelListTemp[i].PowerPack.IsWork)
                        {
                            tpr.PowerStepConfig = testParameter.PowerStepConfig;
                            Global.Global.ChannelListTemp[i].PowerPack.PowerStepConfig = testParameter.PowerStepConfig;
                        }
                        else
                        {
                            tpr.PowerStepConfig = Global.Global.ChannelListTemp[i].PowerPack.PowerStepConfig;
                        }

                        Global.Global.ChannelListTemp[i].TestParameter = tpr;
                        Global.Global.ChannelListTemp[i].TitleFlag = 0;
                    }
                }
                else {

                    UIMessageDialog.ShowMessageDialog(this, "当前电源步骤与其他使用相同电源的电源步骤参数不同，请重新确认。", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                    return;
                }
            }
            else {

                bool isHaveCrossPower = false;
                PowerPack crossPowerPack = null;
                int crossPowerIndex = 0;



                foreach (var each in Global.Global.powerPackList) {
                    string keyEach = each.Key;
                    List<string> keyEachList = keyEach.Split(',').ToList();

                    foreach (var eachPowerStr in powerStrList) {
                        if (keyEachList.Contains(eachPowerStr)) {
                            isHaveCrossPower = true;
                            crossPowerPack = each.Value;
                            crossPowerIndex = int.Parse(eachPowerStr[3].ToString());
                            break;
                        }
                    }
                }



                if (isHaveCrossPower ) {


                    //判断所选通道是否与正在使用电源组的通道相同
                    var isAllSame = crossPowerPack.ChannelList
                        .OrderBy(each => each.Index)
                        .Zip(Global.Global.ChannelListTemp.OrderBy(each => each.Index), (item1, item2) => new {
                            IsIndexSame = item1.Index == item2.Index
                        });

                    if (! isAllSame.All(each => each.IsIndexSame)) {

                        string crossChannel = string.Join(",", crossPowerPack.ChannelList.Select(each => (each.Index + 1).ToString()));

                        UIMessageDialog.ShowMessageDialog(this, "当前电源步骤中所使用的电源" + (crossPowerIndex) + "已经在通道" + crossChannel + "中所使用且电源步骤与当前不同，请重新确认。", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                        return;
                    }

                }

                PowerPack newPowerPack = new PowerPack();

                foreach (var each in powerStrList) {

                    int powerIndex = int.Parse(each[3].ToString()) - 1;

                    newPowerPack.Powers.Add(Global.Global.PowerList[powerIndex]);
                }

                newPowerPack.PowerStepConfig = testParameter.PowerStepConfig;


                for (int i = 0; i < Global.Global.ChannelListTemp.Count; i++)
                {
                    Channel nowChannel = Global.Global.ChannelListTemp[i];
                    nowChannel.PowerPack = newPowerPack;


                    if (!newPowerPack.ChannelList.Contains(nowChannel))
                    {
                        newPowerPack.ChannelList.Add(nowChannel);
                    }


                    Global.Global.ChannelListTemp[i].State = "stop";
                    Global.Global.ChannelListTemp[i].RunningTime = new TimeSpan(0, 0, 0);

                    TestParameter tpr = new TestParameter();
                    tpr.ID = testParameter.ID;
                    tpr.ParaName = testParameter.ParaName;
                    tpr.Remarks = testParameter.Remarks;
                    tpr.ProductModel = testParameter.ProductModel;
                    tpr.BatchNumber = testParameter.BatchNumber;
                    tpr.CheckInterval = testParameter.CheckInterval;

                    tpr.PowerStepConfig = testParameter.PowerStepConfig;

                    tpr.HighTemp = testParameter.HighTemp;
                    tpr.LowTemp = testParameter.LowTemp;
                    tpr.HighTime = testParameter.HighTime;
                    tpr.LowTime = testParameter.LowTime;
                    tpr.XieLv = testParameter.XieLv;
                    tpr.TestCycs = testParameter.TestCycs;
                    tpr.BeforTemp = testParameter.BeforTemp;
                    tpr.BeforTime = testParameter.BeforTime;
                    tpr.AfterTemp = testParameter.AfterTemp;
                    tpr.AfterTime = testParameter.AfterTime;
                    tpr.IsLineContrl = testParameter.IsLineContrl;
                    tpr.StratPos = testParameter.StratPos;
                    tpr.TempContrl = testParameter.TempContrl;
                    tpr.Ysfz = testParameter.Ysfz;

                    tpr.isStatic = testParameter.isStatic;



                    Global.Global.ChannelListTemp[i].TestParameter = tpr;
                    Global.Global.ChannelListTemp[i].TitleFlag = 0;
                }
            }

            for (int i = 0; i < Global.Global.ChannelListTemp.Count; i++)
            {
                if (Global.Global.ChannelListTemp[i].IsCurrentChannel)
                {
                    this.refresh(); // 调用委托
                }
            }
            this.Close();
            return;

        }

        private void cfgGrid_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (!isWorker)
            {
                btnModify_Click(sender, e);
            }
            else
            {
                this.btnPick_Click(sender, e);
            }
        }

    }
}
